package cn.santi.controller;

import cn.santi.domain.PkgState;
import cn.santi.emuns.R;
import cn.santi.service.PkgStateService;
import cn.santi.utli.DateTool;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/state")
public class PkgStateController {
    @Autowired
    private PkgStateService sa;
    private final Path fileStorageLocation = Paths.get("E://hbx/").toAbsolutePath().normalize();

    //显示搜索动态列表
    @GetMapping("/rankstatestate")
    public R rankstatestate(String result, String type) {
        QueryWrapper<PkgState> wrapper = new QueryWrapper<>();
        wrapper.eq("classify", type).eq("state", 0).like("title", result);
        return R.ok(sa.list(wrapper));
    }

    //根据id查询动态
    @GetMapping("/showstatebyid")
    public R showstatebyid(int id) {
        QueryWrapper<PkgState> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        return R.ok(sa.list(wrapper));
    }

    //根据序号查询列表
    @GetMapping("/showstate")
    public R showstate() {
        QueryWrapper<PkgState> wrapper = new QueryWrapper<>();
        wrapper.eq("state", 0).orderByDesc("sequence");
        return R.ok(sa.list(wrapper));
    }

    @GetMapping("/showAboutUs")
    public R showAboutUs(String type) { //查询关于我们
        LambdaQueryWrapper<PkgState> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PkgState::getClassify, type).eq(PkgState::getState, 10);
        return R.ok(sa.getOne(wrapper));
    }

    @GetMapping("/updAboutUs")
    public R updAboutUs(String type, String data) { //修改关于我们
        LambdaQueryWrapper<PkgState> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(PkgState::getClassify, type);
        PkgState pkgState = sa.getOne(wrapper1);
        if (pkgState == null) {
            PkgState pkg = new PkgState();
            pkg.setClassify(type);
            pkg.setMinute(data);
            pkg.setDate(DateTool.gettime());
            pkg.setState(10);
            sa.save(pkgState);
            return R.fail("未找到该类型");
        } else {
            pkgState.setMinute(data);
            pkgState.setDate(DateTool.gettime());
            boolean wrapper = sa.updateById(pkgState);
            if (wrapper) {
                return R.ok("修改成功");
            } else {
                return R.fail("修改失败");
            }
        }
    }


    @GetMapping("/Allrank")
    public R Allrank(String text, String result) {//后台动态排序
//        System.out.println("Allrank:text:"+text);
        LambdaQueryWrapper<PkgState> wrapper = new LambdaQueryWrapper<>();
        switch (text) {
            case "all"://全部分类(全部):(除了"关于我们")
                wrapper.ne(PkgState::getClassify, "关于我们");
//                wrapper.eq(PkgState::getClassify, "最新动态")//这种也可以
//                        .or()
//                        .eq(PkgState::getClassify, "服务介绍");
                break;
            case "Dynamic"://最新动态
                wrapper.eq(PkgState::getClassify, "最新动态");
                break;
            case "introduce"://服务介绍
                wrapper.eq(PkgState::getClassify, "服务介绍");
                break;
            case "normal"://正常
                wrapper.eq(PkgState::getState, 0);
                break;
            case "forbidden"://停用
                wrapper.eq(PkgState::getState, 1);
                break;
            case "newest"://最新
                wrapper.ne(PkgState::getClassify, "关于我们");
                wrapper.orderByDesc(PkgState::getDate);
                break;
            case "recommend"://首页推荐
                wrapper.eq(PkgState::getHomerecommended, "1");
                break;
            case "top"://置顶
                wrapper.eq(PkgState::getTop, "1");
                break;
            case "search"://置顶
                wrapper.like(PkgState::getTitle, result);
                break;
            default:
                return R.fail("参数错误");
        }
        if (text.equals("newest")) {
            return R.ok(sa.list(wrapper));
        }
        wrapper.orderByAsc(PkgState::getSequence);
//        System.out.println("wrapper:"+wrapper);
        System.out.println("Allrank:wrapper:" + sa.list(wrapper));
        return R.ok(sa.list(wrapper));
    }

    @GetMapping("/addPkgState")
    public R addPkgState(PkgState pkgState) {//添加动态
        System.out.println("addPkgStatepkgState:" + pkgState);
        pkgState.setState(0);
        pkgState.setDate(DateTool.gettime());
        boolean save = sa.save(pkgState);
        if (!save) {
            return R.fail("添加失败");
        }
        return R.ok("添加成功");
    }

    @GetMapping("/updDynamic")
    public R updDynamic(PkgState pkgState) { //修改动态
        System.out.println(pkgState);
        boolean b = sa.updateById(pkgState);
        if (b) {
            return R.ok("修改成功");
        } else {
            return R.fail("修改失败");
        }
    }

    @GetMapping("/updDynamicState")
    public R updDynamicState(Integer id, String type) { //修改动态状态（0启 1停）
        System.out.println("updDynamicStateid:" + id + "," + type);
        LambdaUpdateWrapper<PkgState> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(PkgState::getId, id);
        switch (type) {
            case "preview"://启用
                wrapper.set(PkgState::getState, 0);
                break;
            case "Deactivated"://停用(不可见)
                wrapper.set(PkgState::getState, 1);
                break;
            case "deleteDynamic"://删除
                boolean b = sa.removeById(id);
                if (!b) {
                    return R.fail("删除失败");
                } else {
                    return R.ok("删除成功");
                }
            case "HomeRecommended"://推荐到首页
                wrapper.set(PkgState::getHomerecommended, "1");
                break;
            case "top"://置顶
                wrapper.set(PkgState::getTop, "1");
                break;
            default:
                return R.fail("参数错误");
        }
        boolean update = sa.update(wrapper);
        if (!update) {
            return R.fail("修改失败");
        } else {
            return R.ok("修改成功");
        }
    }

    //显示图片
    @GetMapping("/images/{filename:.+}")
    public ResponseEntity<Resource> serveFile(@PathVariable String filename) {
        System.out.println(filename + "=====");
        try {
            Path file = this.fileStorageLocation.resolve(filename).normalize();
            Resource resource = new UrlResource(file.toUri());
            if (resource.exists() || resource.isReadable()) {
                return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"").contentType(MediaType.IMAGE_JPEG).body(resource);
            } else {
                throw new RuntimeException("Could not read file: " + filename);
            }

        } catch (Exception e) {
            return ResponseEntity.ok().build();
        }
    }

    //保存到本地
    @PostMapping("/upload")
    public R handleFileUpload(@RequestParam("file") MultipartFile file) {
        System.out.println(file);
        if (file.isEmpty()) {
            return R.fail("文件不能为空");
        }
        try {
            // 指定文件保存的路径
            Path storagePath = Paths.get("E://hbx/");
            if (!Files.exists(storagePath)) {
                Files.createDirectories(storagePath);
            }

            // 生成新的文件名，使用UUID的前8位
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFilename = UUID.randomUUID().toString().substring(0, 5) + fileExtension;
            Path targetPath = storagePath.resolve(newFilename);

            // 保存文件
            Files.copy(file.getInputStream(), targetPath);
            Map<Object, Object> map = new HashMap<>();
            map.put("newFilename", newFilename);
            map.put("targetPath", "state/images/" + newFilename);
            return R.ok(map);
        } catch (IOException e) {
            e.printStackTrace();
            return R.fail();
        }
    }

}
